package Test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class lockTest implements Runnable {
    int tickets = 50;
    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            lock.lock();
            //包装在需要保证安全的资源外侧
            if (tickets > 0) {
                System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets-- + "张票");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println("票已售完！");
                break;
            }
        }
    }

    public static void main(String[] args) {
        // 创建实例Runnable接口类对象
        Test.tickets t = new tickets();
        // 创建多线程
        new Thread(t, "窗口1").start();
        new Thread(t, "窗口2").start();
        new Thread(t, "窗口3").start();

    }

}